/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.h5;

import cn.easyplatform.dao.BizDao;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.h5.RoleVo;
import cn.easyplatform.type.FieldType;
import cn.easyplatform.type.IResponseMessage;

import java.util.ArrayList;
import java.util.List;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class GetRoleCmd extends AbstractCommand<SimpleRequestMessage> {

	private final static String sql = "SELECT a.roleId,a.name,b.userId FROM sys_user_role_info b,sys_role_info a WHERE a.roleId=b.roleId and b.userId in (SELECT c.userId FROM sys_user_org_info d,sys_user_info c WHERE d.orgId = ? AND c.userId = d.userId AND c.state = 1) ORDER BY a.roleId";

	/**
	 * @param req
	 */
	public GetRoleCmd(SimpleRequestMessage req) {
		super(req);
	}

	@Override
	public IResponseMessage<?> execute(CommandContext cc) {
		try {
			BizDao dao = cc.getBizDao();
			List<FieldDo> params = new ArrayList<FieldDo>(1);
			params.add(new FieldDo(FieldType.VARCHAR, cc.getUser().getOrg()
					.getId()));
			List<FieldDo[]> result = dao.selectList(sql, params);
			List<RoleVo> groups = new ArrayList<RoleVo>();
			RoleVo gv = null;
			for (FieldDo[] fields : result) {
				String roleId = fields[0].getValue().toString();
				String name = fields[1].getValue() == null ? "" : fields[1]
						.getValue().toString();
				String user = fields[2].getValue() == null ? "" : fields[2]
						.getValue().toString();
				if (gv == null || !gv.getId().equals(roleId)) {
					gv = new RoleVo(roleId, name);
					groups.add(gv);
				}
				gv.addUser(user);
			}
			return new SimpleResponseMessage(groups);
		} catch (Exception ex) {
			return new SimpleResponseMessage();
		}
	}

}
